
# 初始化读取环境变量
from settings import get_settings
get_settings()

# 初始化日志配置
from utils.log_utils import initRootLogger
initRootLogger("my-chat_logs")

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from api import chatApi, llmApi
from api.utils import register_exception_handler
from contextlib import asynccontextmanager
from db import create_db_and_tables
from db.utils import init_llm_factory
from middleware.record_time import record_time_middleware
from middleware.request_id import request_id_middleware

@asynccontextmanager
async def lifespan(app: FastAPI):
    # 初始化启动数据
    create_db_and_tables()
    init_llm_factory()
    
    yield

app = FastAPI(root_path='/api/v1', lifespan=lifespan)

# 同一异常处理
register_exception_handler(app)

# 添加中间件
app.middleware('http')(record_time_middleware) # 记录请求处理时间
app.middleware('http')(request_id_middleware) # 生成请求唯一ID

# 配置支持跨域访问
origins = [
    "http://localhost:5173"
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 引用子路由
app.include_router(chatApi)
app.include_router(llmApi)
